package com.lkk.cg.action;

import com.lkk.cg.base.BaseAction;
import com.lkk.cg.domain.Role;
import com.lkk.cg.domain.User;
import com.lkk.cg.util.QueryHelper;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * Created by lkk on 2014/11/27.
 */
@Controller
@Scope("prototype")
public class UserManageAction extends BaseAction<User> {

    private Long roleId;

    /**
     * 列表
     */
    public String list() throws Exception {

        QueryHelper queryHelper = new QueryHelper(User.class, "u");
        queryHelper.preparePageBean(userService, getPageNum(), getPageSize());

        return "list";
    }

    /**
     * 删除
     */
    public String delete() throws Exception {

        userService.delete(model.getId());

        return "toList";
    }

    /**
     * 添加页面
     */
    public String addUI() throws Exception {

        prepareRoleList();
        return "saveUI";
    }

    /**
     * 添加
     */
    @InputConfig(methodName = "prepareRoleList")
    public String add() throws Exception {

        model.setPassword(DigestUtils.md5Hex("123456"));
        model.setRole(roleService.getById(roleId));
        userService.save(model);

        return "toList";
    }

    public void validateAdd(){
        User user = userService.getByLoginName(model.getLoginName());
        if (user != null)
            addActionError("用户名已经存在！");
    }

    /**
     * 修改页面
     */
    public String editUI() throws Exception {

        prepareRoleList();

        //准备数据回显
        User user = userService.getById(model.getId());
        ActionContext.getContext().getValueStack().push(user);
        roleId = user.getRole().getId();

        return "saveUI";
    }

    /**
     * 修改
     */
    @InputConfig(methodName = "prepareRoleList")
    public String edit() throws Exception {

        //获得数据
        User user = userService.getById(model.getId());

        //更新数据
        user.setName(model.getName());
        //todo 不能修改用户名
        //user.setLoginName(model.getLoginName());
        user.setDepartment(model.getDepartment());
        user.setEmail(model.getEmail());
        user.setRole(roleService.getById(roleId));

        //保存到数据库
        userService.update(user);

        return "toList";
    }


    /**
     * 重置密码
     *
     * @return
     */
    public String initPassword() {

        userService.initPassword(model.getId());

        return "toList";
    }

    public String prepareRoleList() {

        List<Role> roleList = roleService.getAll();
        ActionContext.getContext().put("roleList", roleList);

        return "saveUI";
    }


    public Long getRoleId() {
        return roleId;
    }

    public void setRoleId(Long roleId) {
        this.roleId = roleId;
    }

}
